#!/bin/bash
#Some functions copied from dracut, to extract kernel cmdline options

AWK=/bin/awk 
BLOCKDEVB=/sbin/blockdev 
DD=/bin/dd 
GREP=/bin/grep 
PARTED=/usr/sbin/parted 
SED=/bin/sed 
SYNC=/bin/sync 
TR=/usr/bin/tr 
MKSWAP=/sbin/mkswap 
SORT=/bin/sort
LSBLK=/bin/lsblk
str_replace() {
    local in="$1"; local s="$2"; local r="$3"
    local out=''

    while strstr "${in}" "$s"; do
        chop="${in%%$s*}"
        out="${out}${chop# }$r"
        in="${in#*$s}"
    done
    echo "${out}${in}"
}

_getcmdline() {
    local _line
    unset _line
    if [ -z "$CMDLINE" ]; then
        if [ -e /etc/cmdline ]; then
            while read _line; do
                CMDLINE_ETC="$CMDLINE_ETC $_line";
            done </etc/cmdline;
        fi
        read CMDLINE </proc/cmdline;
        CMDLINE="$CMDLINE $CMDLINE_ETC"
    fi
}

_dogetarg() {
    local _o _val _doecho
    unset _val
    unset _o
    unset _doecho
    _getcmdline

    for _o in $CMDLINE; do
        if [ "${_o%%=*}" = "${1%%=*}" ]; then
            if [ -n "${1#*=}" -a "${1#*=*}" != "${1}" ]; then
                # if $1 has a "=<value>", we want the exact match
                if [ "$_o" = "$1" ]; then
                    _val="1";
                    unset _doecho
                fi
                continue
            fi

            if [ "${_o#*=}" = "$_o" ]; then
                # if cmdline argument has no "=<value>", we assume "=1"
                _val="1";
                unset _doecho
                continue
            fi

            _val=${_o#*=};
            _doecho=1
        fi
    done
    if [ -n "$_val" ]; then
        [ "x$_doecho" != "x" ] && echo "$_val";
        return 0;
    fi
    return 1;
}

getarg() {
    while [ $# -gt 0 ]; do
        case $1 in
            -y) if _dogetarg $2 >/dev/null; then
                    echo 1
                    [ "$RD_DEBUG" = "yes" ] && set -x
                    return 0
                fi
                shift 2;;
            -n) if _dogetarg $2 >/dev/null; then
                    echo 0;
                    [ "$RD_DEBUG" = "yes" ] && set -x
                    return 1
                fi
                shift 2;;
            *)  if _dogetarg $1; then
                    [ "$RD_DEBUG" = "yes" ] && set -x
                    return 0;
                fi
                shift;;
        esac
    done
    [ "$RD_DEBUG" = "yes" ] && set -x
    return 1
}


